package com.usian.service.impl;

import com.usian.CatNode;
import com.usian.CatResult;
import com.usian.mapper.TbItemCatMapper;
import com.usian.pojo.TbItemCat;
import com.usian.pojo.TbItemCatExample;
import com.usian.redis.RedisClient;
import com.usian.service.ItemCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ItemCategoryServiceImpl implements ItemCategoryService {

    @Autowired
    private TbItemCatMapper tbItemCatMapper;

    @Value("${PROTAL_CATRESULT_KEY}")
    private String PROTAL_CATRESULT_KEY;

    @Autowired
    private RedisClient redisClient;

    @Override
    public List<TbItemCat> selectItemCategoryByParentId(Long id) {

        TbItemCatExample example =new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andStatusEqualTo(1);
        criteria.andParentIdEqualTo(id);
        List<TbItemCat> list = tbItemCatMapper.selectByExample(example);
        return list;
    }

    @Override
    public CatResult selectItemCategoryAll() {

        CatResult catResult =new CatResult();
        //去redis缓存查询
        catResult = (CatResult)redisClient.get(PROTAL_CATRESULT_KEY);
        if(catResult!=null){
            return catResult;
        }
        catResult.setData(this.getCatList(0L));

        //缓存redis
        redisClient.set(PROTAL_CATRESULT_KEY,catResult);

        return catResult;
    }

    public List<?> getCatList(Long parentId){

        //递归查询
        TbItemCatExample example =new TbItemCatExample();
        TbItemCatExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        List<TbItemCat> itemCatList = tbItemCatMapper.selectByExample(example);

        List resultList = new ArrayList();

        int count=0;
        for(TbItemCat itemCat :itemCatList){   //60
            //true ==1   false==0
            if(itemCat.getIsParent()){
                //1:把当前的节点数据封装到 catNode
                CatNode catNode = new CatNode();
                catNode.setName(itemCat.getName());
                //2:递归查询查子节点
                catNode.setItem(getCatList(itemCat.getId()));
                //3:catNode的结果封装到catResult  data
                resultList.add(catNode);

                //4：固定查18条
                count ++;
                if(count==18){
                    break;
                }
            }else{
                //resultList.add(itemCat.getName());
                CatNode catNode = new CatNode();
                catNode.setName(itemCat.getName());
                resultList.add(catNode);
            }
        }

        return resultList;

    }
}
